package com.danskin.wechat.webapi;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.danskin.wechat.constant.DanskinConstants;
import com.danskin.wechat.entity.CustGiftRecord;
import com.danskin.wechat.entity.CustInfo;
import com.danskin.wechat.entity.CustInfoEx;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.service.CouponService;
import com.danskin.wechat.service.CrmBrandInfoService;
import com.danskin.wechat.service.CustGiftRecordService;
import com.danskin.wechat.service.CustInfoExService;
import com.danskin.wechat.service.CustInfoService;
import com.danskin.wechat.service.CustPointRecordService;
import com.danskin.wechat.service.GiftConfigService;
import com.danskin.wechat.service.GiftService;
import com.danskin.wechat.service.WechatMsgTemplateService;
import com.danskin.wechat.util.BeanUtil;
import com.danskin.wechat.util.DateUtils;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.vo.CustInfoVo;

@RestController
@RequestMapping("api/giftCert")
public class NewCustGiftController extends BaseApiController {

	@Resource
	CustInfoService custInfoService;

	@Resource
	GiftConfigService giftConfigService;

	@Resource
	CustGiftRecordService custGiftRecordService;

	@Resource
	CouponService custCouponRecordService;

	@Resource
	CustPointRecordService custPointRecordService;

	@Resource
	CrmBrandInfoService crmBrandInfoService;

	@Resource
	CustInfoExService custInfoExService;

	@Resource
	GiftService giftService;

	@Resource
	WechatMsgTemplateService wechatMsgTemplateService;

	/**
	 * 判断用户信息完整性
	 * 
	 * @param wxOpenId
	 * @return
	 */
	@RequestMapping(value = "judgeGetNewCustAuthOrNot/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object judgeCustInfoFull(@RequestBody Map<String, Object> map, @PathVariable("appId") String appId) {

		if (!isValid("openId", map)) {
			return getError("用户微信openId不能为空");
		}

		LogUtil.info("========判断用户信息完整性参数：wxOpenId=" + map.get("openId").toString());

		try {

			// 根据用户微信openId获取用户信息
			CustInfoVo custInfoDto = custInfoService.queryCustInfoDtoByOpenId(map.get("openId").toString());
			if (custInfoDto == null || StringUtils.isBlank(custInfoDto.getMemberId())) {
				return getError("获取用户信息异常");
			}

			// 验证用户是否已领取过奖品
			CustInfoEx param = new CustInfoEx();
			param.setMemberId(custInfoDto.getMemberId());
			List<CustInfoEx> custInfoExList = custInfoExService.selectCustInfoExList(param);
			if (CollectionUtils.isEmpty(custInfoExList)) {
				return getError("获取用户信息异常");
			}
			if (custInfoExList.get(0).getIsGetGift() == DanskinConstants.CUST_INFO_EX_IS_GET_GIFT_ALREADY_GET) {
				return getError("该用户已领取过奖品");
			}

			return new AccessResponse<String>("0", "该用户可领取新人礼");
		} catch (Exception e) {
			LogUtil.error("=========判断用户信息完整性异常");
			return getError("系统异常");
		}
	}

	/**
	 * 领取新人礼
	 * 
	 * @param wxOpenId
	 * @return
	 */
	@RequestMapping(value = "getNewCustGift/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object getNewCustGift(@RequestBody Map<String, Object> map, @PathVariable("appId") String appId) {
		if (!isValid("openId", map)) {
			return getError("用户微信openId不能为空");
		}
		if (!isValid("activityType", map)) {
			return getError("活动类型不能为空");
		}
		if (!isValid("name", map)) {
			return getError("用户姓名不能为空");
		}
		if (!isValid("gender", map)) {
			return getError("用户性别不能为空");
		}
		if (!isValid("birthday", map)) {
			return getError("用户生日不能为空");
		}
		if (StringUtils.isBlank(appId)) {
			return getError("appId不能为空");
		}

		LogUtil.info("=========领取新人礼参数：wxOpenId=" + map.get("openId").toString() + "&activityType="
				+ map.get("activityType").toString() + "&name=" + map.get("name").toString() + "&gender="
				+ map.get("gender").toString() + "&birthday=" + map.get("birthday").toString());

		// 封装用户信息用于更新用户信息
		CustInfo custInfo = new CustInfo();
		custInfo.setName(map.get("name").toString());
		custInfo.setGender(Integer.valueOf(map.get("gender") + ""));
		custInfo.setBirthday(DateUtils.str2Date(map.get("birthday").toString()));
		if (isValid("province", map)) {
			custInfo.setProvince(map.get("province").toString());
		}
		if (isValid("city", map)) {
			custInfo.setCity(map.get("city").toString());
		}
		if (isValid("district", map)) {
			custInfo.setDistrict(map.get("district").toString());
		}

		custInfo = custInfoService.saveCustInfoSelective(custInfo, map.get("openId").toString());

		if (custInfo == null) {
			LogUtil.error("=======领取新人礼时更新用户信息异常");
			return getError("用户信息更新异常");
		}

		// 获取活动奖品前的验证
		AccessResponse<String> validateResult = giftService.validateGetActivityPrize(map.get("openId").toString(),
				Integer.valueOf(map.get("activityType") + ""));

		if (!StringUtils.equals(validateResult.getErrorCode(), "0")) { // 验证不通过,直接返回提示信息
			return validateResult;
		} else { // 验证通过，执行领取奖品
			WxMediaPlatform mediaPlatform = this.getMPWithAccessToken(appId);
			if (mediaPlatform != null) {

				Object resultObject = giftService.getActivityPrize(map.get("openId").toString(),
						Integer.valueOf(map.get("activityType") + ""), mediaPlatform);

				if (resultObject == null) {
					return getError("活动奖品领取失败");
				} else {
					return new AccessResponse<Object>("0", "活动奖品领取成功", resultObject);
				}
			} else {
				return getError("无效的AppId。");
			}
		}
	}

	/**
	 * 新人礼查询用户未领取的实物
	 * 
	 * @param custId
	 * @return
	 */
	@RequestMapping(value = "selectCustNotGetGoods/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object selectCustNotGetGoods(@RequestBody Map<String, Object> map, @PathVariable("appId") String appId) {
		if (!isValid("openId", map)) {
			return getError("用户微信openId不能为空");
		}
		LogUtil.info("========新人礼查询用户未领取的实物参数：wxOpenId=" + map.get("openId").toString());

		List<CustGiftRecord> goodsRecordList = new ArrayList<CustGiftRecord>();

		// 根据用户微信openId获取用户信息
		CustInfoVo custInfoDto = custInfoService.queryCustInfoDtoByOpenId(map.get("openId").toString());

		try {
			// 封装查询条件
			CustGiftRecord param = new CustGiftRecord();
			param.setCustExId(custInfoDto.getCustExId());
			// 领取状态：未领取
			param.setStatus(DanskinConstants.CUST_GOODS_RECODE_STATUS_NOT_GET);
			// 活动类型：新人礼
			param.setActivityName("新人礼");

			// 执行查询
			goodsRecordList = custGiftRecordService.selectCustGiftRecordList(param);

			if (CollectionUtils.isNotEmpty(goodsRecordList)) {
				return new AccessResponse<CustGiftRecord>("0", "查询成功", goodsRecordList.get(0));
			} else {
				return new AccessResponse<CustGiftRecord>("0", "查询成功", null);
			}
		} catch (NumberFormatException e) {
			LogUtil.error("=======新人礼查询用户未领取的实物异常", e);
		}
		return getError("系统异常");
	}

	/**
	 * 更新用户实物领取状态为已领取
	 * 
	 * @param recordId
	 * @return
	 */
	@RequestMapping(value = "updateCustGoodsAlreadyGet/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object updateCustGoodsAlreadyGet(@RequestBody Map<String, Object> map, @PathVariable("appId") String appId) {
		LogUtil.info("========更新用户实物领取状态为已领取参数：" + ToStringBuilder.reflectionToString(map));

		if (!isValid("openId", map)) {
			return getError("用户微信openId不能为空");
		}

		if (!isValid("id", map)) {
			return getError("奖品ID不能为空");
		}

		if (!isValid("consigneeName", map)) {
			return getError("领取人姓名不能为空");
		}

		if (StringUtils.isBlank(appId)) {
			return getError("appId不能为空");
		}

		// 根据主键判断存不存在该已抽中的实物
		CustGiftRecord goodsRecord = custGiftRecordService
				.selectCustGiftRecordById(Integer.valueOf(map.get("id") + ""));
		if (goodsRecord == null || StringUtils.isBlank(goodsRecord.getGoodsName())) {
			return new AccessResponse<String>("-1", "没有该实物被抽中");
		}

		int updateCount = 0;

		String accessToken = getMPAccessToken(appId);

		CustGiftRecord param = new CustGiftRecord();
		try {
			param = (CustGiftRecord) BeanUtil.mapToObject(map, CustGiftRecord.class);
		} catch (Exception e) {
			LogUtil.error("=========Map转换成Bean异常", e);
			return getError("系统异常");
		}

		try {
			// 把状态更新为已领取
			param.setStatus(DanskinConstants.CUST_GOODS_RECODE_STATUS_ALREADY_GET);

			// 执行更新操作
			updateCount = custGiftRecordService.updateCustGiftRecord(param);

			if (updateCount > 0) {
				// 根据用户微信openId获取用户信息
				CustInfoVo custInfoDto = custInfoService.queryCustInfoDtoByOpenId(map.get("openId").toString());
				if (custInfoDto == null || StringUtils.isBlank(custInfoDto.getMemberId())) {
					return new AccessResponse<String>("-1", "获取用户信息异常");
				}

				// 给用户发送实物新人礼领取消息通知
				wechatMsgTemplateService.sendCustGetGoodsMsg(accessToken, appId, map.get("openId").toString(),
						custInfoDto.getName(), map.get("consigneeName").toString(), goodsRecord.getGoodsName());
				return new AccessResponse<String>("0", "用户实物领取成功");
			}
		} catch (Exception e) {
			LogUtil.error("======更新用户实物领取状态为已领取异常", e);
		}
		return getError("系统异常");
	}

}
